package org.scboy.rbac.service.imp;

import java.util.List;
import java.util.Locale;
import java.util.UUID;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.rbac.dao.RbacUserAccountDao;
import org.scboy.rbac.service.UserAccountService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserAccountServiceImp implements UserAccountService {

	@Autowired
	EntityFactory factory;
	
	@Override
	public Page page(Model model) {
		RbacUserAccountDao dao=factory.getDao(RbacUserAccountDao.class);
		return dao.page(model);
	}

	@Override
	public List<Model> getAcccounts(String userId) {
		RbacUserAccountDao dao=factory.getDao(RbacUserAccountDao.class);
		return dao.select(Model.create().add("userId", userId));
	}

	@Override
	public Model getAccount(String userId, String loginName) {
		RbacUserAccountDao dao=factory.getDao(RbacUserAccountDao.class);
		return dao.get(
			Model.create().add("userId", userId).add("loginAccount", loginName)
		);
	}

	@Override
	public Model getAccount(String id) {
		RbacUserAccountDao dao=factory.getDao(RbacUserAccountDao.class);
		return dao.get(Model.create().add("id", id));
	}

	@Override
	public Model getAccountByLoginName(String loginName) {
		RbacUserAccountDao dao=factory.getDao(RbacUserAccountDao.class);
		return dao.get(
			Model.create().add("loginAccount", loginName)
		);
	}

	@Override
	public boolean checkState(String id) {
		RbacUserAccountDao dao=factory.getDao(RbacUserAccountDao.class);
		Model model=getAccount(id);
		if(model==null){
			return false;
		}
		model.add("loginState", model.getInt("loginState")==0?1:0);
		int resultCount=dao.update(model);
		if(resultCount>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean add(Model model) {
		RbacUserAccountDao dao=factory.getDao(RbacUserAccountDao.class);
		//验证帐号是否存在。
		Model accountModel=getAccountByLoginName(model.getString("loginAccount").toUpperCase(Locale.ENGLISH));
		if(accountModel!=null){
			return false;
		}
		model.add("id", UUID.randomUUID().toString());
		model.add("loginAccount", model.getString("loginAccount").toUpperCase(Locale.ENGLISH));
		model.add("loginState", 1);
		int resultCount=dao.insert(model);
		if(resultCount>0){
			return true;
		}else{
			return false;
		}
	}

}
